/*
 * vim: ts=4 sw=4 fdm=marker noet tw=78 ai
 * %%LICENSE%%
 */
#include <sys/cdefs.h>
#ifdef __FBSDID
__FBSDID("$Coar$");
#endif

#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

#include "util.h"
/*
 * I like my API better than POSIX getline(3). Sorry folks.
 *
 * Gets a line from a given FILE handle. Returns the string length including
 * line terminator, but not including string terminator. Sets *ptr to the
 * newly allocated string for the current line.
 * Returns 0 on EOF and on read errors.
 */
size_t fgetline(FILE *fp, char **ptr)
{
	char *retval, line[1024];
	size_t pos, r;
	
	pos = 0;
	retval = NULL;
	
	while( fgets(line, sizeof(line), fp) != NULL )
	{
		r = strlen(line);
		retval = reallocf(retval, r+pos+1);
		if( retval == NULL )
			return 0;
		(void)memcpy(retval+pos, line, r);
		pos += r;
		if( line[r-1] == '\n' )
			break;
	}
	
	if( retval != NULL )
		retval[pos] = '\0';

	*ptr = retval;
	
	return (pos);
}

size_t fgetfile(FILE *fp, char **ptr)
{
	char *retval, buf[8192];
	size_t pos, r;

	pos = 0;
	retval = NULL;

	while( !feof(fp) )
	{
		r = fread(buf, sizeof(char), sizeof(buf), fp);
		if( r == 0 )
			break;
		retval = reallocf(retval, r+pos+1);
		if( retval == NULL )
			return 0;
		(void)memcpy(retval+pos, buf, r);
		pos += r;
	}
	
	if( retval != NULL )
		retval[pos] = '\0';

	*ptr = retval;

	return (pos);
}

char *strtolower(char *in)
{
	int ch;

	if( in != NULL )
	{
		while( (ch = (int)*in) != '\0' )
		{
			*in = (char)tolower(ch);
			++in;
		}
	}

	return (in);
}
